var app = getApp()
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    customBar: app.globalData.customBar,
    API_BASE_URL: util.API_BASE_URL,
    token: '',
    changePwdShow: false,
    code: '',
    userInfo: {},
    nickName: '',
    authInfo: {
      wx_user_tx: '',
      wx_user_name: '',
      phoneNumber: ''
    },
    menuList: [
      {
        icon: '/images/wm.png',
        title: '我的信息',
        url: '/pages/userInfo/userInfo'
      }, {
        icon: '/images/wdkh.png',
        title: '我的客户',
        url: '/pages/myClient/myClient'
      }, {
        icon: '/images/xgmm.png',
        title: '修改密码',
        url: '/pages/myFeedback/myFeedback',
        operationType: 'changePwd'
      }, {
        icon: '/images/pj.png',
        title: '我的反馈',
        url: '/pages/fankuiOrJianyi/fankuiOrJianyi'
      }, {
        icon: '/images/fxewm.png',
        title: '分享二维码',
        url: '/pages/shareCode/shareCode'
      }
    ],
    nickNamePopupShow: false, //修改昵称弹窗
    oldPassword: '', //旧密码
    newPassword: '' //新密码
  },
  passwordInput(e) {
    const { type } = e.currentTarget.dataset;
    // 使用正则表达式过滤所有中文字符
    const filteredValue = e.detail.value.replace(/[\u4E00-\u9FA5]/g, '');
    if (type == 'old') {
      this.setData({ oldPassword: filteredValue })
    } else if (type == 'new') {
      this.setData({ newPassword: filteredValue })
    }
    // 返回处理后的值（需要与 setData 保持同步）
    return filteredValue;
  },
  //登出
  logout() {
    wx.showModal({
      title: '提示',
      content: '是否退出登录？',
      success(res) {
        if (res.confirm) {
          wx.removeStorageSync('X-EOA-TOKEN')
          util.showMsg({
            msg: '退出登录成功',
            duration: 1500,
            success: () => {
              wx.reLaunch({
                url: '/pages/login/login',
              })
            }
          })
        }
      }
    })
  },
  //前往我的信息页面
  myInfo() {
    const token = wx.getStorageSync('token');
    if (token) {
      wx.navigateTo({
        url: '/pages/userInfo/userInfo',
      })
    }
  },
  confirm() {
    const _this = this;
    const { oldPassword, newPassword } = this.data;
    if (!oldPassword) return util.showMsg("旧密码不能为空")
    if (!newPassword) return util.showMsg("新密码不能为空")
    if (oldPassword == newPassword) return util.showMsg("新密码不能和旧密码一样！")

    util.request('/itf/common/orgitem/uploadUserPassword.json', {
      old_password: util.encode64(oldPassword),
      new_password: util.encode64(newPassword)
    }, "POST").then(res => {
      if (res.success) {
        util.showMsg({
          msg: res.message,
          duration: 1500,
          success: () => {
            _this.setData({ changePwdShow: false })
          }
        })
      } else {
        util.showMsg({ msg: res.message || res.msg })
      }
    });
  },
  cancel() {
    this.setData({ changePwdShow: false })
  },
  updateUser(params) {
    const _this = this;
    util.request('/itf/common/orgitem/uploadUserName.json', params, "POST").then(res => {
      if (res.success) {
        let result = res.data;
        _this.setData({
          userInfo: result
        })
      } else {
        util.showMsg({ msg: res.message || res.msg })
      }
    });
  },
  //打开修改昵称弹窗
  openNickNamePopup() {
    this.setData({
      nickName: this.data.userInfo.user_name,
      nickNamePopupShow: true
    })
  },
  //关闭修改昵称弹窗
  closeNickNamePopup() {
    this.setData({
      nickNamePopupShow: false
    })
  },
  //确认修改昵称
  onNickNameConfirm() {
    const _this = this;
    util.request('/itf/common/orgitem/uploadUserName.json', {
      user_name: _this.data.nickName
    }, "POST").then(res => {
      if (res.success) {
        util.showMsg({
          msg: res.message,
          duration: 1000,
          success: () => {
            _this.setData({
              'userInfo.user_name': _this.data.nickName
            })
            _this.closeNickNamePopup()
          }
        })
      } else {
        util.showMsg({ msg: res.message || res.msg })
      }
    });
  },
  //修改头像
  chooseImageTap: function (e) {
    let that = this;
    let goodsIndex = e.currentTarget.dataset.goodsIndex;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#F32F1D",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage('album', goodsIndex)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage('camera', goodsIndex)
          }
        }
      }
    })
  },
  chooseWxImage: function (type, goodsIndex) {
    let _this = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      count: 1,
      success: function (res) {
        var tempFilePaths = res.tempFilePaths
        let info = wx.getAccountInfoSync()
        for (const key in tempFilePaths) {
          wx.uploadFile({
            url: util.API_BASE_URL + 'itf/common/att/edit.do',
            filePath: tempFilePaths[key],
            name: 'file',
            formData: {
              'dir': 'hongpei',
            },
            header: {
              'maAppId': info.miniProgram.appId || '',
              'content-type': 'multipart/form-data',
              'X-EOA-TOKEN': wx.getStorageSync('X-EOA-TOKEN')
            },
            success: function (res) {
              var picObj = JSON.parse(res.data);
              _this.uploadHeadImage(picObj.id);
            },
            fail(err) {
              console.error(err);
            }
          })
        }
      }
    })
  },
  uploadHeadImage(billid) {
    const _this = this;
    util.request('/itf/common/orgitem/uploadHeadImage.json', {
      billid
    }, "POST").then(res => {
      if (res.success) {
        util.showMsg({ msg: res.message || res.msg })
        _this.setData({
          'userInfo.head_img': ""
        })
        _this.setData({
          'userInfo.head_img': _this.data.API_BASE_URL + util.removeLeadingSlash(res.data) + "&X-EOA-TOKEN="+wx.getStorageSync('X-EOA-TOKEN')
        })
      } else {
        util.showMsg({ msg: res.message || res.msg })
      }
    });
  },
  getPhoneNumber(e) {
    let _this = this,
      phoneCode = '';
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      phoneCode = e.detail.code; //登录凭证
      //获取手机号接口
      util.request('/itf/common/home/login/getPhoneNumber.json', {
        phoneCode
      }).then(res => {
        if (res.success) {
          _this.setData({
            'authInfo.phoneNumber': res.data.phoneNumber
          })
        } else {
          util.showMsg({ msg: res.message || res.msg })
        }
      });
    } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '为了获得更好的服务，请允许授权'
      })
    }
  },
  //获取数量
  getNumber() {
    const _this = this;
    util.request('/itf/common/home/login/getNumber.json').then(res => {
      if (res.success) {
        let list = _this.data.menuList;
        list.forEach(item => {
          switch (item.title) {
            case '收藏':
              item.num = res.data.scNumber;
              break;
            case '我的行程':
              item.num = res.data.wdxcNumber;
              break;
            case '行程方案':
              item.num = res.data.xcfaNumber;
              break;
          }
        })
        _this.setData({
          menuList: list
        })
      } else {
        util.showMsg({ msg: res.message || res.msg })
      }
    });
  },
  //获取用户信息
  getLoginInfo() {
    const _this = this;
    util.request('/itf/common/orgitem/getLoginInfo.json').then(res => {
      if (res.success) {
        let result = res.data;
        result.head_img = _this.data.API_BASE_URL + util.removeLeadingSlash(result.head_img) + "&X-EOA-TOKEN="+wx.getStorageSync('X-EOA-TOKEN');
        _this.setData({ userInfo: result })
      } else {
        util.showMsg({ msg: res.message || res.msg })
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  // 页面跳转
  switchPage(e) {
    const { link, operationType } = e.currentTarget.dataset;
    if (operationType == 'changePwd') {
      //修改密码
      this.setData({
        oldPassword: '',
        newPassword: '',
        changePwdShow: true
      })
      return
    }
    wx.navigateTo({
      url: link
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const _this = this;
    this.getLoginInfo();
    // wx.login({
    //   success: function (res) {
    //     if (res.code) {
    //       _this.setData({
    //         code: res.code
    //       })
    //       util.request('/itf/common/home/login/validateLogon.json', {
    //         code: res.code,
    //       }, "POST").then(res => {
    //         if (res.success) {
    //           //存储用户信息
    //           wx.setStorageSync('userInfo', res.data.userInfo);
    //           wx.setStorageSync('token', res.data.token);
    //           _this.setData({
    //             userInfo: res.data.userInfo,
    //             token: res.data.token,
    //             changePwdShow: false
    //           })
    //         }
    //       });
    //     }
    //   }
    // });
    // const token = wx.getStorageSync('token')
    // if (token) {
    //   this.getNumber();
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.closeNickNamePopup()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})